package com.example.wechat_applet.service.impl;

import com.example.wechat_applet.pojo.LoginUser;
import com.example.wechat_applet.pojo.Result;
import com.example.wechat_applet.pojo.User;
import com.example.wechat_applet.service.LoginService;
import com.example.wechat_applet.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService
{
    @Autowired
    private AuthenticationManager authenticationManager;

//    @Autowired
//    private RedisCache redisCache;

    public Result login(User user) {
        //Authentication 进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getName(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //如果认证没通过，给出对应提示
        if(Objects.isNull(authenticate))
        {
            throw new RuntimeException("登录失败");
        }
        //如果认证通过，使用用户id生成jwt
        LoginUser loginUser = (LoginUser)authenticate.getPrincipal();
        Integer id = loginUser.getUser().getId();
        System.out.println(id);
        String jwt = JwtUtil.createJWT(id.toString());

//        //把完整的用户信息存入redis 用户id作为key
//        redisCache.setCacheObject("login:"+id,loginUser);

        Map<String,String> map = new HashMap<>();
        map.put("token",jwt);

        return new Result(200,"登录成功！",map);
    }

    @Override
    public Result logout() {
        return null;
    }

    //登出
//    @Override
//    public ResponseResult logout()
//    {
//        LoginUser loginUser = (LoginUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//        Long id = loginUser.getUser().getId();
//
//        //删除redis中的
//        redisCache.deleteObject("login:"+id);
//
//        return new ResponseResult(200,"登出成功");
//    }
}
